package com.bootdo.app.alipay.controller;

import com.bootdo.app.alipay.service.EmpowerService;
import com.bootdo.common.utils.R;
import com.bootdo.app.alipay.config.AlipayConfig;
import com.bootdo.app.alipay.util.AlipayUtil;
import com.bootdo.payee.domain.PaymentCodeDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Desc 支付宝授权
 *          用于获取支付宝收款户用户id
 * @date 2019/11/7
 *
 */
@RestController
@RequestMapping("/app")
public class EmpowerController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private EmpowerService empowerService;


    @PostMapping("/alipayTranAccSave")
    public R alipayTranAccSave(PaymentCodeDO paymentCode) {
        try{
            return empowerService.alipayTranAccSave(paymentCode);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>alipayTranAccSave接口报错:未知错误-{}，错误栈-{}<<<<<<<<<<",e.getMessage(), e);
            return R.error(-1,"系统繁忙");
        }

    }

    @RequestMapping("/callbackTraAccSave")
    public void callbackTraAccSave(HttpServletRequest request) {

        try{
            empowerService.callbackTraAccSave(request);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>callbackTraAccSave接口报错:未知错误-{}，错误栈-{}<<<<<<<<<<",e.getMessage(), e);
        }

    }


    @PostMapping("/open")
    public R open(String userId) throws Exception {
        //页面回调地址 必须与应用中的设置一样
        String returnUrl = "http://192.168.31.208:8020/sifa/bbb.html?id=" + userId;
        //回调地址必须经encode
        returnUrl = URLEncoder.encode(returnUrl, "UTF-8");
        //重定向到授权页面
        String url = AlipayConfig.ALIPAY_URL+"?app_id=" + AlipayConfig.APP_ID + "&scope=auth_user&redirect_uri=" + returnUrl;
        String urls = URLEncoder.encode(url, "UTF-8");
        Map<String, String> map = new HashMap<>();
        map.put("url", urls);
        map.put("qCode", url);
        return R.ok(map);
    }

    @PostMapping("/imf")
    public void returnImf(String authCode, String userId){
        //获取支付宝GET过来反馈信息
        String accessToken= AlipayUtil.buildRequest(authCode);
        if(accessToken!=null && accessToken!=""){
            String imf  =  AlipayUtil.get(accessToken);
            System.out.println(imf);
            System.out.println("userId" + userId);
        }
    }




}
